package br.ufs.dcomp.lsp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SendingHandler implements Runnable {

	Sender sender;
	DatagramSocket socket;
	LSPParams params;
	
	public SendingHandler(Sender sender, DatagramSocket socket, LSPParams params){
		this.sender = sender;
		this.socket = socket;
		this.params = params;
	}
	
	@Override
	public void run() {
		try {
			while(this.sender.isActive()){
				// Se existe pacote a ser enviado e nenhum esperando ser reconhecido
				if(!this.sender.getPacketsToSend().isEmpty() && this.sender.getPacketWaitingForAck() == -1){
					
					Pack packet = this.sender.getPacketsToSend().take();
					DatagramPacket sendData = new DatagramPacket(packet.getPayload(),
							packet.getPayload().length, packet.getHost(), packet.getPort());
					socket.send(sendData);
					
					// Seta o Id do pacote enviado para esperar seu ACK
					this.sender.setPacketWaitingForAck(packet.getSequenceNumber());
					
				}else if(!this.sender.getPacketsToSend().isEmpty() && this.sender.getPacketWaitingForAck() != -1){
					new Thread(new EpochHandler(params.epoch, params.epochLimit));
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			System.out.println("Socket: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("IO: " + e.getMessage());
		} catch (InterruptedException e) {
			System.out.println("Interrupted: " + e.getMessage());
		}
	}

}
